#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N=55;
char grid[N][N];
bool vis[N][N],use[N][N];
ll m,n,t,ans;
int dx[8]={1,0,-1,0,1,1,-1,-1};
int dy[8]={0,1,0,-1,1,-1,1,-1}; 
void bfs_col(int x,int y){
	queue<pair<int,int>> q;
	q.push({x,y});
	while(q.size()){
		auto f=q.front();q.pop();
		x=f.first;y=f.second;
		for (int i=0;i<4;i++){
			int px=x+dx[i],py=y+dy[i];
			if (px>=1 && px<=m && py>=1 && py<=n && !vis[px][py] && grid[px][py]=='1'){
				vis[px][py]=1;
				q.push({px,py});
			}
		}
	}
}
bool bfs_out(int x,int y){
	for (int i=1;i<=m;i++){
		for (int j=1;j<=n;j++){
			use[i][j]=0;
		}
	}
	queue<pair<int,int>> q;
	q.push({x,y});use[x][y]=1;
	while(q.size()){
		auto f=q.front();q.pop();
		x=f.first;y=f.second;
		if (x==1 || y==1 || x==m || y==n)return true;
		for (int i=0;i<8;i++){
			int px=x+dx[i],py=y+dy[i];
			if (px>=1 && px<=m && py>=1 && py<=n && !use[px][py] && grid[px][py]=='0'){
				
				use[px][py]=1;
				q.push({px,py});
			}
		}
	}
	return false;
}
void solve(){
	ans=0;
	cin>>m>>n;
	for (int i=1;i<=m;i++){
		for (int j=1;j<=n;j++){
			cin>>grid[i][j];
			vis[i][j]=0;
		}
	}
	for (int i=1;i<=m;i++){
		for (int j=1;j<=n;j++){
			if (!vis[i][j] && grid[i][j]=='1'){
				vis[i][j]=1; 
				bfs_col(i,j);
				if (bfs_out(i,j))ans++;
			}
		}
	}
	cout<<ans<<endl;
}
int main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>t;
	while(t--){
		solve();
	}
	return 0;
} 
